/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IDE_formularios;

import ConexaoDados.InteracaoDados;
import OPC.ConexaoOPC;
import OPC.OPCException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafish.clients.opc.exception.*;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author erikjan
 */
public class AssTag {
    
    private FrmAssTag frm;
    
    private DefaultListModel modeloTagsNaoAssociadas = new DefaultListModel();
    private DefaultListModel modeloTagsAssociadas = new DefaultListModel();
    private List<String> listTagsRemovidas;    

    /**
     * Creates new form AssTag
     */
    public AssTag(FrmAssTag form) throws SQLException {
        
        frm = form;
        
        frm.listaTagsNaoAssociadas.setModel(modeloTagsNaoAssociadas);
        frm.listaTagsAssociadas.setModel(modeloTagsAssociadas);
        listTagsRemovidas = new ArrayList<>();
    }
        
    public void Listar_servidores() throws SQLException {
        
        //ok - testado
        InteracaoDados dados = new InteracaoDados();
        
        ResultSet result_sql = dados.consulta("select * from servidor_opc");
        
        if (result_sql.next()==true) {//verifica se existe resultado da consulta        
            frm.cbnome_servidor.removeAllItems();//limpa o combo
            frm.cbnome_servidor.addItem("");
            result_sql.beforeFirst();//volta o ponteiro o inicio do ResultSet
                   
            while (result_sql.next()) {                
                frm.cbnome_servidor.addItem(result_sql.getInt(1)+" - "+result_sql.getString("nome")+" - "+result_sql.getString("host"));             
            }
            
            result_sql.close();
        }
    }
        
    public void Listar_malhas() throws SQLException{
        
        InteracaoDados dados = new InteracaoDados();
        
        ResultSet result_sql = dados.consulta("select * from malha");
        
        if (result_sql.next()==true){
            frm.cbnome_malha.removeAllItems();
            frm.cbnome_malha.addItem("");
            result_sql.beforeFirst();
        }
        
        while (result_sql.next()){
            frm.cbnome_malha.addItem(result_sql.getInt(1)+" - "+result_sql.getString("desc_malha"));
        }
    }    
    
    public void Listar_Tags_Cadastradas() throws SQLException{
        if(frm.cbnome_servidor.getSelectedIndex()>0 && frm.cbnome_malha.getSelectedIndex()==0){
            modeloTagsAssociadas.clear();
            if(listTagsRemovidas.isEmpty()!=true){
            for(int i = 0 ; i<listTagsRemovidas.size() ; i++){
                modeloTagsNaoAssociadas.addElement(listTagsRemovidas.get(i).toString().trim());                
                }
                listTagsRemovidas.clear();
            }
        }        
        if(frm.cbnome_servidor.getSelectedIndex()>0 && frm.cbnome_malha.getSelectedIndex()>0){
        if(!"".equals(frm.cbnome_servidor.getSelectedItem().toString()) && !"".equals(frm.cbnome_malha.getSelectedItem().toString())){
            
            InteracaoDados dados = new InteracaoDados();
            String [] servidor = frm.cbnome_servidor.getSelectedItem().toString().split("-");
            String [] malha = frm.cbnome_malha.getSelectedItem().toString().split("-");
           
            int idservidor = Integer.parseInt(servidor[0].toString().trim());
            int idmalha = Integer.parseInt(malha[0].toString().trim());
            
            try (ResultSet result_sql = dados.consulta("select * from associatag where servidoropc_fk="+idservidor+" and tbmalha_fk="+idmalha+"")) {
                modeloTagsAssociadas.clear();
                while (result_sql.next()){
                     modeloTagsAssociadas.addElement(result_sql.getString("NomeTag").toString().trim());
                     if(modeloTagsNaoAssociadas.contains(result_sql.getString("NomeTag").toString().trim())){
                            modeloTagsNaoAssociadas.removeElement(result_sql.getString("NomeTag").toString().trim());                         
                            if(listTagsRemovidas.contains(result_sql.getString("NomeTag").toString().trim())!=true){
                                listTagsRemovidas.add(result_sql.getString("NomeTag").toString().trim());
                            }
                        }
                    }
                }
            }        
        }
    }

    public void conectarServidor() {
        if(frm.cbnome_servidor.isValid()){
        
        try {
            Listar_Tags_Cadastradas();            
        } catch (SQLException ex) {
            Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
        }    
                        
        modeloTagsNaoAssociadas.clear();
                        
        String [] dados = frm.cbnome_servidor.getSelectedItem().toString().split("-");
                    
        ConexaoOPC.newInstance(dados[2].trim(), dados[1].trim(), 1);    

        try {
            ConexaoOPC.getCurrentInstance().conectar();            
            
        } catch (OPCException | UnableAddGroupException | ConnectivityException | UnableAddItemException ex) {
            Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Erro de conexao com o servidor OPC", "Conexao", JOptionPane.ERROR_MESSAGE);
        }
            
        String[] ListaDeItens = null;
        String[] ListaDeItens2 = null;


        try {
            ListaDeItens = ConexaoOPC.getCurrentInstance().ListarDispositivos();
        } catch (ConnectivityException ex) {
            Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
        }
        List<String> ListaDeNos = new ArrayList<String>(); 
        if(ListaDeItens != null){
            for(int i = 0; i < ListaDeItens.length ; i++){
            ListaDeNos.add(ListaDeItens[i].toString());
            }
        }
 
        for(int j = 0 ; j < ListaDeNos.size() ; j++){
            System.out.println(ListaDeNos.get(j));                        
            String[] ListaDeItens2test = null;
            
            try {
                ListaDeItens2test = ConexaoOPC.getCurrentInstance().ListarDispositivosDeDispositivos(ListaDeNos.get(j));
            } catch (ConnectivityException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnableBrowseBranchException ex) {
                //Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
                //continue;
            }            
            
            if(ListaDeItens2test!=null){
                if(ListaDeItens2test.length >0){
                    for(int i = 0 ; i<ListaDeItens2test.length ; i++){
                        System.out.println(ListaDeItens2test[i].toString());
                        String insereString = ListaDeNos.get(j)+"."+ListaDeItens2test[i].toString();
                        ListaDeNos.add(insereString.toString());
                        System.out.println(ListaDeNos);
                    }
                }
            }
            
            
            if(ListaDeNos.get(j).toString().trim().indexOf(frm.jTextField1.getText().toString().trim()) != -1 && frm.jCheckBox1.isSelected() == true){
            
            try {                        
                ListaDeItens2 = ConexaoOPC.getCurrentInstance().getItem(ListaDeNos.get(j));
                
            } catch (UnableBrowseLeafException ex) {
                
            } catch (UnableIBrowseException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnableAddGroupException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnableAddItemException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            
                List<String> ListaDeTags = Arrays.asList(ListaDeItens2);
                for(String x : ListaDeTags){                    
                    String[] xsplit = x.split(";");
                        if(modeloTagsAssociadas.contains(xsplit[2].toString().trim())!=true){
                            modeloTagsNaoAssociadas.addElement(xsplit[2].toString().trim());  
                            System.out.println(xsplit[2].toString().trim());
                        }                    
                }
                
              }
            if(frm.jCheckBox1.isSelected() == false){
                
            try {                        
                ListaDeItens2 = ConexaoOPC.getCurrentInstance().getItem(ListaDeNos.get(j));
                
            } catch (UnableBrowseLeafException ex) {
                
            } catch (UnableIBrowseException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnableAddGroupException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnableAddItemException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            
                List<String> ListaDeTags = Arrays.asList(ListaDeItens2);
                for(String x : ListaDeTags){                    
                    String[] xsplit = x.split(";");
                        if(modeloTagsAssociadas.contains(xsplit[2].toString().trim())!=true){
                            modeloTagsNaoAssociadas.addElement(xsplit[2].toString().trim());  
                            System.out.println(xsplit[2].toString().trim());
                        }                    
                }                
                
            }
            
            
            }
        }
    }
    
    public void associaTag() {
        if(frm.cbnome_servidor.isValid() && frm.cbnome_servidor.isValid()){
                
                if(!"".equals(frm.cbnome_servidor.getSelectedItem().toString()) && frm.cbnome_servidor.getSelectedIndex()>0){
                    
                    if(!"".equals(frm.cbnome_malha.getSelectedItem().toString()) && frm.cbnome_malha.getSelectedIndex()>0){
                        
                        if(!"".equals(frm.jComboBox2.getSelectedItem().toString()) && frm.jComboBox2.getSelectedIndex()>0){
                            
                            if(!"".equals(frm.jComboBox3.getSelectedItem().toString()) && frm.jComboBox3.getSelectedIndex()>0){
                                
                                if(frm.listaTagsNaoAssociadas.isSelectionEmpty()!=true){
                                
                                    InteracaoDados gravar = new InteracaoDados();

                                    String [] servidor = frm.cbnome_servidor.getSelectedItem().toString().split("-");
                                    String [] malha = frm.cbnome_malha.getSelectedItem().toString().split("-");

                                    int idservidor = Integer.parseInt(servidor[0].trim());
                                    int idmalha = Integer.parseInt(malha[0].trim());
                                    System.out.println(idservidor);
                                    System.out.println(idmalha);
                                    try {
                                        gravar.inserir_tag(frm.listaTagsNaoAssociadas.getSelectedValue().toString().trim(), frm.jComboBox2.getSelectedItem().toString().trim(), frm.jComboBox3.getSelectedItem().toString().trim(), idmalha, idservidor);
                                    } catch (SQLException ex) {
                                        Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
                                    }

                                    JOptionPane.showMessageDialog(null, "Tag associada com sucesso.", "Associar Tags", JOptionPane.INFORMATION_MESSAGE);
                                            
                                    try {
                                        Listar_Tags_Cadastradas();
                                    } catch (SQLException ex) {
                                        Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
                                    }                                    
                                }
                                
                                else{
                                    JOptionPane.showMessageDialog(frm, "Favor Selecionar Tag");
                                }                                    
                            }
                            else{
                                JOptionPane.showMessageDialog(frm, "Favor Selecionar Grandeza");
                            }
                        }
                        else{
                            JOptionPane.showMessageDialog(frm, "Favor Selecionar Tipo");
                        }
                    }
                    else{
                        JOptionPane.showMessageDialog(frm, "Favor Selecionar Malha");
                    }                    
                }
                else{
                    JOptionPane.showMessageDialog(frm, "Favor Selecionar Servidor");
                }    
            }
    }
    
    public void removerTag() {
         if(frm.listaTagsAssociadas.isSelectionEmpty()!=true){
            
            String nomeTag = frm.listaTagsAssociadas.getSelectedValue().toString().trim();
            
            InteracaoDados apagar = new InteracaoDados();
            
            try {
                apagar.deleta("DELETE FROM AipetroTest.associatag WHERE NomeTag='"+nomeTag+"'");
                
                JOptionPane.showMessageDialog(null, "Informação deletada com sucesso", "Apagar Tag", JOptionPane.INFORMATION_MESSAGE);
                
                modeloTagsAssociadas.removeElement(nomeTag);
                
                if(frm.cbnome_malha.getSelectedIndex()>0 && modeloTagsNaoAssociadas.isEmpty()!=true){
                modeloTagsNaoAssociadas.addElement(nomeTag);
                }
                
            } catch (SQLException ex) {
                Logger.getLogger(AssTag.class.getName()).log(Level.SEVERE, null, ex);
                
                JOptionPane.showMessageDialog(null, "Erro na deleção da informação", "Erro!", JOptionPane.ERROR);
            }
        }
        else
            JOptionPane.showMessageDialog(frm, "Favor Selecionar Tag");  
    }
}
